<template>
  <!-- 配置文件 -->
  <div class="tablePageWarp">
    <div class="commonSelectWidth table-page-search-wrapper">
      <a-row :gutter="16"> 

         <a-col :md="3" :sm="16">
          <car-model-code-select
              :query="{ time:instantUpdateTime, selectAll: false}"
              :has-all="false"
              :clear="true"
              v-model="queryParam.modelCode"
              @change="tableRefresh(true)"
              style="width:100%"
            ></car-model-code-select>
         </a-col>

        <a-col :md="3" :sm="16">
          <VersionTypeSelect v-model="queryParam.versionType" @change="tableRefresh(true)" :clear="true" style="width:100%"/>
        </a-col>
        <a-col
          :md="6"
          :sm="24"
        >
          <a-select
            v-model="queryParam.ecuModuleId"
            allow-clear
            :filter-option="false"
            :placeholder="$t('pleaseSelect')+$t('lingjian')"
            style="width:100%"
            mode="multiple"
            :maxTagCount="1"
            @search="getEcuList"
            @focus="getEcuList"
            @change="(val) => {changeEcuList(val);tableRefresh(true)}"
            :notFoundContent="isSearch?$t('noData'):$t('ecuNameSearch')"
          >
            <a-select-option
              v-for="(item,index) in ecuList"
              :key="index"
              :value="item.ecuModuleId"
              :title="`${item.name}/${item.ecuModuleId}`"
            >
              {{ `${item.name}/${item.ecuModuleId}` }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col
          :md="6"
          :sm="24"
        >
          <a-input
            v-model.trim="queryParam.name"
            :placeholder="$t('pleaseInput')+$t('configFileVersion').toLowerCase()"
            @keyup.enter="tableRefresh(true)"
            allowClear
          />
        </a-col>
        <a-col
          :md="6"
          :sm="24"
        >
          <div class="searchBtns">
            <a-button-group>
              <auth-button type="primary" :auth="softwarePerms.configFile.view" @click="tableRefresh(true)">
                <i class="iconfont icon-chazhao"></i>
                {{ $t('inquiry') }}
              </auth-button>
              <a-button @click="initiSelectValue">
                <i class="iconfont icon-qingkong"></i>
                {{ $t('clear') }}
              </a-button>
            </a-button-group>
            <auth-button :auth="softwarePerms.configFile.add" @click="handleAddEdit()">
              <i class="iconfont icon-xinjian"></i>
              {{ $t('version') }}
            </auth-button>
          </div>
        </a-col>
      </a-row>
    </div>
    <s-table
      class="h100"
      ref="table"
      size="default"
      :rowKey="(record,index)=>index"
      :columns="columns"
      :data="loadData"
      :scrollX="900"
    >
      <template
        slot="partNumber"
        slot-scope="text,record"
      >
        <span v-if="record.ecu">{{ record.ecu.ecuModuleId }}</span>
        <span v-else>-</span>
      </template>
      <template
        slot="modelCode"
        slot-scope="text,record"
      >
        <span v-if="record.modelCode">{{ record.modelCode }}</span>
        <span v-else>-</span>
      </template>
      <template
        slot="partName"
        slot-scope="text,record"
      >
        <span v-if="record.ecu">{{ record.ecu.name }}</span>
        <span v-else>-</span>
      </template>
      <template
        slot="configurationFile"
        slot-scope="text,record"
      >
        <span v-if="record.ecu">{{ record.ecu.ecuConfigDid }}</span>
        <span v-else>-</span>
      </template>
      <template
        slot="configurationFileCode"
        slot-scope="text,record"
      >
        {{ record.configSoftwareCode?record.configSoftwareCode:'-' }}
      </template>
      <template
        slot="configFileVersion"
        slot-scope="text,record"
      >
        <a @click="handleAddEdit(record,true)">
          {{ record.name }}
        </a>
      </template>
      <template
        slot="createTime"
        slot-scope="text"
      >
        <span>{{ text?$options.filters.moment(text):'_' }}</span>
      </template>
      <span
        slot="action"
        slot-scope="text,record"
        class="tableOperateSty"
      >
        <div>
          <auth-button v-if="record.versionType === 'TEST'"
            :auth="softwarePerms.configFile.edit"
            type="primary"
            :ghost="true"
            size="small"
            @click="handleAddEdit(record)"
          ><i class="iconfont icon-xiugai"/>{{ $t('edit') }}</auth-button>
          <auth-button v-if="record.versionType === 'TEST'"
            type="danger"
            :ghost="true"
            size="small"
            :auth="softwarePerms.configFile.delete"
            @click="deleteList(record)"
          ><i class="iconfont icon-shanchu3 deleteUlr"/>{{ $t('delete') }}</auth-button>
        </div>
      </span>
    </s-table>
  </div>
</template>
<script>
import { mapMutations } from 'vuex'
import HasNoPermissionTip from '@/components/HasNoPermissionTip'
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import { STable } from '@/components'
import { minxinDrawerUse } from '@/utils/mixin'
import NewEditconfigFile from './components/NewEditconfigFile.vue'
import AuthButton from '@/components/AuthButton'
import AuthText from '@/components/AuthText'
import VersionTypeSelect from '@/views/components/VersionTypeSelect'
import { softwarePerms } from '@/config/permission/index'
import { columns } from './config'
import CarModelCodeSelect from '@/views/components/CarModelCodeSelect'
import { mapState } from 'vuex'


export default {
  name: 'CongfigFileList',
  mixins: [minxinDrawerUse],
  components: {
    TableEllipsis,
    HasNoPermissionTip,
    STable,
    NewEditconfigFile,
    VersionTypeSelect,
    AuthButton,
    AuthText,
    CarModelCodeSelect
  },
  data () {
    return {
      columns,
      softwarePerms,
      queryParam: {},
      selectedEcuList: [], // 已选中ecu
      ecuList: [],
      isSearch: false,
      deleteId: []
    }
  },
  created () {
  },
  mounted () {
    this.initiSelectValue()
  },
  computed: {
    ...mapState({
        instantUpdateTime: (state) => state.app.instantUpdateTime
    })
  },
  methods: {
    tableRefresh (bool = false) {
      const vm = this
      vm.$nextTick(() => {
        vm.$refs.table.refresh(bool)
      })
    },
    loadData (parameter) {
      // 如果是全部则不传值给后端
      const vm = this
      const JnqueryParam = JSON.parse(JSON.stringify(vm.queryParam))
      // eslint-disable-next-line no-restricted-syntax
      for (const key in JnqueryParam) {
        if (JnqueryParam[key] === '') {
          JnqueryParam[key] = undefined
        }
      }
      return this.$api.getConfigFileList({ ...JnqueryParam, ...parameter })
    },
    // 下拉框 重置和初始化
    initiSelectValue () {
      this.queryParam = {}
      this.tableRefresh(true)
    },
    // 获取已选中ecu的下拉数据
    changeEcuList (value) {
      const vm = this
      vm.selectedEcuList = []
      if (value.length) {
        value.forEach((ecuModuleId) => {
          const selectItem = vm.ecuList.filter((item) => item.ecuModuleId === ecuModuleId)
          // vm.selectedEcuList = vm.selectedEcuList.concat(selectItem)
        })
      } else {
        vm.ecuList = []
      }
    },
    // 获取零件选项
    getEcuList (value = '') {
      const vm = this
      vm.ecuList = []
      vm.isSearch = false
      if (value) {
        vm.isSearch = true
        vm.$api.getAllEcu({ name: value.trim(), containConfigSoftwareCode: true }).then(response => {
          const filterEcuList = vm.filterSelectEcuList(response.data || [])
          vm.ecuList = vm.selectedEcuList.concat(filterEcuList)
        }).catch(() => {
          vm.ecuList = vm.selectedEcuList
        })
      } else {
        vm.ecuList = vm.selectedEcuList
      }
    },
    // 从搜索出来的ecu中排除已选中的ecu
    filterSelectEcuList (searchEcuList) {
      const vm = this
      let filterEcu = searchEcuList
      const selectEcuModuleId = vm.queryParam.ecuModuleId
      if (selectEcuModuleId && selectEcuModuleId.length && filterEcu.length) {
        selectEcuModuleId.forEach((ecuModuleId) => {
          filterEcu = filterEcu.filter((item) => item.ecuModuleId !== ecuModuleId)
        })
      }
      return filterEcu
    },
    // 新建编辑版本
    handleAddEdit (recordData = {}, isDetail = false) {
      const vm = this
      const buttons = this.getRightDrawerFooterButtons()
      // eslint-disable-next-line no-param-reassign
      recordData.isDetail = isDetail
      const vars = { recordData }
      let title = ''
      if (recordData.id && isDetail) {
        title = vm.$t('configFileVersion') + vm.$t('detail')  + '【'+ (recordData.versionType === 'TEST' ? '测试版' : '定版') +'】';
      } else if (recordData.id && !isDetail) {
        title = vm.$t('edit') + vm.$t('configFileVersion') + ' 【测试版】'
      } else {
        title = vm.$t('new') + vm.$t('configFileVersion') + ' 【测试版】'
      }
      if (!isDetail && !recordData.id) {
        vm.showRightDrawerNoReset(NewEditconfigFile, title, isDetail ? [] : buttons, 'large', vars);
      } else {
        vm.showRightDrawer(NewEditconfigFile, title, isDetail ? [] : buttons, 'large', vars);
      }
    },
    saveData (values) {
      const vm = this
      const params = vm.$commonFun.deepCopy(values)
      params.apiStr = undefined
      return new Promise((resolve, reject) => {
        this.$api[values.apiStr](params).then(res => {
          vm.tableRefresh(!values.id)
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 批量删除
    deleteList (record) {
      const vm = this
      vm.deleteId = [record.id]
      this.$confirm({
        title: vm.$t('deleteConfig'),
        content: '请确认是否删除选中的配置文件？' + `${record.name}` + ' 删除后将无法恢复',
        class: 'confirmStyle',
        icon: '<Icon >',
        width: 378,
        onOk: vm.deleteOk,
        onCancel () { }
      })
    },
    deleteOk () {
      const vm = this
      vm.$api.deleteConfigFile({ ids: vm.deleteId }).then(() => {
        vm.$message.success(vm.$t('successfullyDelete'))
        vm.tableRefresh() // 刷新页面
      })
    }
  }
}
</script>
